package com.example.aop;

import com.example.Service.LogService;
import com.example.pojo.OperateLog;
import com.example.pojo.Result;
import com.example.util.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Aspect //当前类为切面类
@Slf4j
public class TimeAspect {

    @Autowired
    private LogService logService;

//    @Pointcut("execution(* com.example.Service.impl.DeptServiceImpl.*(..))")
//    public void pt(){};

    @Around("@annotation(com.example.anno.LogOperation)")
    public Object recordTime(ProceedingJoinPoint pjp) throws Throwable {
        //记录方法执行开始时间
        long begin = System.currentTimeMillis();
        log.info("begin: {}毫秒",begin);
        //执行原始方法
        Object result = pjp.proceed();

        System.out.println(pjp.getTarget());
        String className=pjp.getTarget().getClass().getName();
        String methodName=pjp.getSignature().getName();
        String medthodParams=Arrays.toString(pjp.getArgs());
        Integer id= ThreadLocalUtil.get();

        //记录方法执行结束时间
        long end = System.currentTimeMillis();
        log.info("end: {}毫秒",end);
        //计算方法执行耗时
        log.info("方法执行耗时: {}毫秒",end-begin);

        logService.insertLog(new OperateLog(null,id, LocalDateTime.now(),className,methodName,medthodParams, Result.success(result).toString(),end-begin));
        return result;
    }


//    @Before("@annotation(com.example.anno.LogOperation)")
//    public void before(){
//        log.info("before------啦啦啦啦啦");
//    }


//    @After("pt()")
//    public void after(){
//        log.info("after----------");
//    }
//
//    @AfterReturning("pt()")
//    public void afterRunning(){
//        log.info("afterRunning");
//    }
//
//    @AfterThrowing("pt()")
//    public void AfterThrowing(){
//        log.info("AfterThrowing");
//    }
}